package com.tydic.serialPort;

import com.tydic.applet.DashboardApplet;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by maliang on 2017/4/24.
 */
public class SerialListener implements SerialPortEventListener {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    private SerialPort serialport;
    private DashboardApplet deviceApplet;
    public SerialListener(){

    }
    public SerialListener(SerialPort serialport, DashboardApplet deviceApplet){
        this.serialport = serialport;
        this.deviceApplet = deviceApplet;
    }
    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {

        switch (serialPortEvent.getEventType()) {

            case SerialPortEvent.BI: // 10 通讯中断
                break;

            case SerialPortEvent.OE: // 7 溢位（溢出）错误

            case SerialPortEvent.FE: // 9 帧错误

            case SerialPortEvent.PE: // 8 奇偶校验错误

            case SerialPortEvent.CD: // 6 载波检测

            case SerialPortEvent.CTS: // 3 清除待发送数据

            case SerialPortEvent.DSR: // 4 待发送数据准备好了

            case SerialPortEvent.RI: // 5 振铃指示

            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 输出缓冲区已清空
                break;

            case SerialPortEvent.DATA_AVAILABLE: // 1 串口存在可用数据
                byte[] data = null;
                try {
            /*        if (serialport == null) {

                    } else {
                        // 读取串口数据
                        data = SerialPortManager.readFromPort(serialport);
                        if(data != null ){
                            String weight = LoadometerParser.parseDs3(data);
                            if(!"".equals(weight)){
                                deviceApplet.setPortData(weight);
                                System.out.println("接收到的信息为："+weight);
                            }
                        }
                    }*/
                } catch (Exception e) {
                    // 发生读取错误时显示错误信息后退出系统
                    logger.error(e.getMessage());
                    System.exit(0);

                }
                break;
        }
    }

    public SerialPort getSerialport() {
        return serialport;
    }

    public void setSerialport(SerialPort serialport) {
        this.serialport = serialport;
    }

    public void setDeviceApplet(DashboardApplet deviceApplet) {
        this.deviceApplet = deviceApplet;
    }

    public DashboardApplet getDeviceApplet() {
        return deviceApplet;
    }
}
